package com.xiaotao.service.impl;

import com.xiaotao.dto.TeamPostDTO;
import com.xiaotao.entity.TeamPost;
import com.xiaotao.entity.UserLike;
import com.xiaotao.mapper.TeamPostMapper;
import com.xiaotao.mapper.UserLikeMapper;
import com.xiaotao.service.TeamPostService;
import com.xiaotao.util.RecommendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class TeamPostServiceImpl implements TeamPostService {

    @Autowired
    private TeamPostMapper teamPostMapper;

    @Autowired
    private UserLikeMapper userLikeMapper;

    @Autowired
    private RecommendUtil recommendUtil;

    // 定义时间格式
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    @Override
    @Transactional
    public TeamPost createPost(Integer userId, TeamPostDTO postDTO) {
        TeamPost post = new TeamPost();
        post.setUserId(userId);
        post.setTitle(postDTO.getTitle());
        post.setContent(postDTO.getContent());
        post.setCategory(postDTO.getCategory());
        post.setMaxMembers(postDTO.getMaxMembers() != null ? postDTO.getMaxMembers() : 10);
        post.setLocation(postDTO.getLocation());
        post.setLatitude(postDTO.getLatitude());
        post.setLongitude(postDTO.getLongitude());

        // 处理时间 - 确保时间格式正确
        if (postDTO.getStartTime() != null) {
            post.setStartTime(postDTO.getStartTime());
        }
        if (postDTO.getEndTime() != null) {
            post.setEndTime(postDTO.getEndTime());
        }

        post.setTagsFromList(postDTO.getTags());

        teamPostMapper.insert(post);
        return teamPostMapper.selectById(post.getId());
    }

    @Override
    public TeamPost getPostById(Long id) {
        TeamPost post = teamPostMapper.selectById(id);
        if (post != null) {
            teamPostMapper.incrementViewCount(id);
        }
        return post;
    }

    @Override
    public List<TeamPost> getPosts(int page, int size) {
        int offset = (page - 1) * size;
        return teamPostMapper.selectPage(offset, size);
    }

    @Override
    public List<TeamPost> getPostsByCategory(String category) {
        return teamPostMapper.selectByCategory(category);
    }

    @Override
    public List<TeamPost> getUserPosts(Integer userId) {
        return teamPostMapper.selectByUserId(userId);
    }

    @Override
    @Transactional
    public TeamPost updatePost(Long postId, Integer userId, TeamPostDTO postDTO) {
        TeamPost existing = teamPostMapper.selectById(postId);
        if (existing == null || !existing.getUserId().equals(userId)) {
            return null;
        }

        existing.setTitle(postDTO.getTitle());
        existing.setContent(postDTO.getContent());
        existing.setCategory(postDTO.getCategory());
        existing.setMaxMembers(postDTO.getMaxMembers());
        existing.setLocation(postDTO.getLocation());
        existing.setLatitude(postDTO.getLatitude());
        existing.setLongitude(postDTO.getLongitude());

        // 处理时间更新
        if (postDTO.getStartTime() != null) {
            existing.setStartTime(postDTO.getStartTime());
        }
        if (postDTO.getEndTime() != null) {
            existing.setEndTime(postDTO.getEndTime());
        }

        existing.setTagsFromList(postDTO.getTags());

        teamPostMapper.update(existing);
        return teamPostMapper.selectById(postId);
    }

    @Override
    @Transactional
    public boolean deletePost(Long postId, Integer userId) {
        TeamPost post = teamPostMapper.selectById(postId);
        if (post == null || !post.getUserId().equals(userId)) {
            return false;
        }
        return teamPostMapper.softDelete(postId) > 0;
    }

    @Override
    @Transactional
    public boolean likePost(Integer userId, Long postId) {
        if (userLikeMapper.countByUserIdAndPostId(userId, postId) > 0) {
            return false;
        }

        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setPostId(postId);
        userLike.setCreateTime(LocalDateTime.now());
        userLikeMapper.insert(userLike);

        teamPostMapper.incrementLikeCount(postId);
        return true;
    }

    @Override
    @Transactional
    public boolean unlikePost(Integer userId, Long postId) {
        int deleted = userLikeMapper.deleteByUserIdAndPostId(userId, postId);
        if (deleted > 0) {
            teamPostMapper.decrementLikeCount(postId);
            return true;
        }
        return false;
    }

    @Override
    public boolean checkLikeStatus(Integer userId, Long postId) {
        return userLikeMapper.countByUserIdAndPostId(userId, postId) > 0;
    }

    @Override
    public List<TeamPost> getUserLikedPosts(Integer userId) {
        return teamPostMapper.selectUserLikedPosts(userId);
    }

    @Override
    public List<TeamPost> getRecommendedPosts(Integer userId) {
        return recommendUtil.getRecommendedPosts(userId);
    }

    @Override
    public void calculateRecommendScores() {
        recommendUtil.calculateAllRecommendScores();
    }
}